const express = require('express');
const router = express.Router();

// 获取所有用户的习惯列表
router.get('/', async (req, res) => {
  try {
    // 查询所有用户的习惯
    const habitsQuery = `
      SELECT h.id, h.title, h.difficulty, h.is_archived, h.created_at, h.user_id, u.email as user_email
      FROM habits h
      LEFT JOIN users u ON h.user_id = u.id
      ORDER BY h.created_at DESC
    `;
    
    const habitsResult = global.db.exec(habitsQuery);
    const habits = [];
    
    if (habitsResult.length > 0) {
      const { columns, values } = habitsResult[0];
      for (const row of values) {
        const habit = {};
        columns.forEach((col, i) => {
          habit[col] = row[i];
        });
        habits.push(habit);
      }
    }
    
    res.json(habits);
  } catch (error) {
    console.error('获取习惯列表错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取习惯统计数据
router.get('/summary', async (req, res) => {
  try {
    // 获取所有习惯总数
    const totalHabitsQuery = `SELECT COUNT(*) as count FROM habits`;
    const totalHabitsResult = global.db.exec(totalHabitsQuery);
    const totalHabits = totalHabitsResult[0].values[0][0];
    
    // 获取已归档习惯数量
    const archivedHabitsQuery = `SELECT COUNT(*) as count FROM habits WHERE is_archived = 1`;
    const archivedHabitsResult = global.db.exec(archivedHabitsQuery);
    const archivedHabits = archivedHabitsResult[0].values[0][0];
    
    // 使用trigger_data字段获取分类信息（如果有的话）
    const categories = [];
    
    res.json({
      total_habits: totalHabits,
      archived_habits: archivedHabits,
      categories
    });
  } catch (error) {
    console.error('获取习惯统计数据错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取推荐习惯
router.get('/recommendations', async (req, res) => {
  try {
    // 查询所有推荐习惯
    const recommendationsQuery = `
      SELECT * FROM habit_recommendations
      ORDER BY category
    `;
    
    const recommendationsResult = global.db.exec(recommendationsQuery);
    const recommendations = [];
    
    if (recommendationsResult.length > 0) {
      const { columns, values } = recommendationsResult[0];
      for (const row of values) {
        const recommendation = {};
        columns.forEach((col, i) => {
          recommendation[col] = row[i];
        });
        recommendations.push(recommendation);
      }
    }
    
    res.json(recommendations);
  } catch (error) {
    console.error('获取推荐习惯列表错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

module.exports = router; 